import { onBeforeMount, ref } from 'vue'

/**
 * 倒计时钩子函数
 * @returns
 * @example
 * const { count, countDown } = useNumDown()
 * const sendCode = () => {console.log("发送验证码")}
 * <button :disabled="count!=0" @click="countDown(5,sendCode)">倒计时 {{ count || '' }} </button>
 *
 */
export function useNumDown() {
  const count = ref<number>(0)
  const timer = ref<number | null>(null)
  const countDown = (second: number, cb: Function) => {
    if (count.value === 0 && timer.value === null) {
      cb()
      count.value = second
      timer.value = setInterval(() => {
        count.value--
        if (count.value === 0) {
          timer.value && clearInterval(timer.value)
          timer.value = null
        }
      }, 1000)
    }
  }
  onBeforeMount(() => {
    timer.value && clearInterval(timer.value)
  })

  return {
    count,
    countDown
  }
}
